import type { Recordable, UserInfo } from '@vben/types';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { LOGIN_PATH } from '@vben/constants';
import { preferences } from '@vben/preferences';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';
import { $t } from '@vben/locales';

import { ElNotification } from 'element-plus';
import { defineStore } from 'pinia';

import { loginApi, logoutApi, getUserInfoApi } from '#/api';


export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  async function authLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;
      
      // 由于设置了 responseReturn: 'data'，成功的响应会直接返回 data 字段内容
      // 如果接口失败，会直接抛出错误进入 catch 块
      const userData = await loginApi({
        loginName: params.username || params.loginName,
        password: params.password,
      });

      // 检查是否有 token
      if (userData?.token) {
        const accessToken = userData.token;
        
        // 将 accessToken 存储到 accessStore 中
        accessStore.setAccessToken(accessToken);

        // 构造用户信息
        userInfo = {
          avatar: userData.avatar || '',
          desc: userData.realName || userData.username,
          homePath: preferences.app.defaultHomePath, // 使用默认首页路径
          userId: userData.id.toString(),
          realName: userData.realName || userData.username,
          roles: userData.role?.roleKey ? [userData.role.roleKey] : ['user'],
          username: userData.username,
          token: accessToken,
        };

        userStore.setUserInfo(userInfo);

        // 持久化用户ID到localStorage，方便页面刷新后获取
        localStorage.setItem('vben-user-id', userData.id.toString());

        // 处理权限数据 - 从菜单权限中提取权限码
        const accessCodes = userData.perms?.map(perm => perm.perms).filter(Boolean) || [];
        accessStore.setAccessCodes(accessCodes);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          // 确保所有状态都设置完成后再跳转
          await new Promise(resolve => setTimeout(resolve, 100)); // 给状态设置一些时间
          
          if (onSuccess) {
            await onSuccess?.();
          } else {
            const targetPath = userInfo.homePath || preferences.app.defaultHomePath;
            console.log('登录成功，跳转到:', targetPath);
            console.log('当前用户信息:', userStore.userInfo);
            await router.push(targetPath);
          }
        }

        ElNotification({
          message: `${$t('authentication.loginSuccessDesc')}:${userInfo.realName}`,
          title: $t('authentication.loginSuccess'),
          type: 'success',
        });
      } else {
        ElNotification({
          message: '登录失败：未获取到有效令牌',
          title: '登录失败',
          type: 'error',
        });
      }
    } catch (error: any) {
      console.error('Login error:', error);
      
      // 从错误响应中提取错误信息
      const errorMessage = error?.response?.data?.message || 
                          error?.message || 
                          '登录失败，请检查用户名和密码';
      
      ElNotification({
        message: errorMessage,
        title: '登录失败',
        type: 'error',
      });
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  async function logout(redirect: boolean = true) {
    try {
      await logoutApi();
    } catch {
      // 不做任何处理
    }
    
    // 清除持久化的用户ID
    localStorage.removeItem('vben-user-id');
    
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }

  async function fetchUserInfo() {
    try {
      // 获取当前用户ID（优先从store获取，其次从localStorage获取）
      const currentUserInfo = userStore.userInfo;
      const userId = currentUserInfo?.userId || localStorage.getItem('vben-user-id');
      
      if (!userId) {
        console.warn('无法获取用户ID，无法刷新用户信息');
    return userStore.userInfo;
      }

      // 尝试从后端重新获取用户信息
      const userData = await getUserInfoApi(userId);
      
      if (userData) {
        // 构造用户信息
        const userInfo: UserInfo = {
          avatar: userData.avatar || '',
          desc: userData.realName || userData.username,
          homePath: preferences.app.defaultHomePath,
          userId: userData.id.toString(),
          realName: userData.realName || userData.username,
          roles: userData.role?.roleKey ? [userData.role.roleKey] : ['user'],
          username: userData.username,
          token: userData.token || accessStore.accessToken || '',
        };

        // 更新用户信息到 store
        userStore.setUserInfo(userInfo);
        
        // 更新持久化的用户ID
        localStorage.setItem('vben-user-id', userData.id.toString());
        
        // 更新权限信息 - 从菜单权限中提取权限码
        const accessCodes = userData.perms?.map(perm => perm.perms).filter(Boolean) || [];
        accessStore.setAccessCodes(accessCodes);
        
        return userInfo;
      }
      
      return userStore.userInfo;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 如果获取失败，返回 store 中的信息（可能为 null）
      return userStore.userInfo;
    }
  }

  function $reset() {
    loginLoading.value = false;
  }

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
  };
});
